package com.itee.javafx.controls;

import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.text.TextAlignment;
import javafx.util.Callback;

import java.text.Format;

/**
 * Created by gonglei on 14-4-23.
 */
public class FormattedTableCellFactory<S, T> implements
        Callback<TableColumn<S, T>, TableCell<S, T>> {
    /**
     * The alignment for both the multiline text and label position within cell.
     */
    private TextAlignment alignment;

    /**
     * Specify a Format if required to format the cell item.
     */
    private Format format;

    public TextAlignment getAlignment() {
        return alignment;
    }

    public Format getFormat() {
        return format;
    }

    public void setAlignment(TextAlignment alignment) {
        this.alignment = alignment;
    }

    public void setFormat(Format format) {
        this.format = format;
    }


    @Override
    public TableCell<S, T> call(TableColumn<S, T> arg0) {
        final TableCell<S, T> cell = new TableCell<S, T>() {
            @Override
            protected void updateItem(T item, boolean empty) {
                if (item == getItem()) {
                    return;
                }
                super.updateItem(item, empty);
                if (item == null) {
                    setText(null);
                    setGraphic(null);
                } else if (item instanceof Node) {
                    setText(null);
                    setGraphic((Node) item);
                } else if (format != null) {
                    setText(format.format(item));
                    setGraphic(null);
                } else {
                    setText(item.toString());
                    setGraphic(null);
                }


            }
        };
        if (alignment == null)
            alignment = TextAlignment.LEFT;
        cell.setTextAlignment(alignment);
        switch (alignment) {
            case CENTER:
                cell.setAlignment(Pos.CENTER);
                break;
            case RIGHT:
                cell.setAlignment(Pos.CENTER_RIGHT);
                break;
            default:
                cell.setAlignment(Pos.CENTER_LEFT);
        }
        return cell;
    }


}
